<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use tool\Auth;

/**
 * 生产密码
 * @param $password
 * @return string
 */
function makePassword($password)
{
    $secret = md5($password . config('whisper.salt'));
    return $secret;
}

/**
 * 检测密码
 * @param $dbPassword
 * @param $inPassword
 * @return bool
 */
function checkPassword($inPassword, $dbPassword) {
	
    return (makePassword($inPassword) == $dbPassword);
}

/**
 * 获取mysql 版本
 * @return string
 */
function getMysqlVersion() {

    $conn = mysqli_connect(
        config('database.hostname') . ":" . config('database.hostport'),
        config('database.username'),
        config('database.password'),
        config('database.database')
    );

    return mysqli_get_server_info($conn);
}

/**
 * 生成layui子孙树
 * @param $data
 * @return array
 */
function makeTree($data) {

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key => $vo) {
        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key => $vo) {
        if($vo['pid'] != 0){
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }

    // 去除杂质
    foreach ($res as $key => $vo) {
        if($vo['pid'] == 0){
            $tree[] = $vo;
        }
    }
    unset($res);

    return $tree;
}

/**
 * 打印调试函数
 * @param $data
 */
function dump($data) {

    echo "<pre>";
    print_r($data);
}

/**
 * 标准返回
 * @param $code
 * @param $data
 * @param $msg
 * @return \think\response\Json
 */
function reMsg($code, $data, $msg) {

    return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
}

/**
 * model返回标准函数
 * @param $code
 * @param $data
 * @param $msg
 * @return array
 */
function modelReMsg($code, $data, $msg) {

    return ['code' => $code, 'data' => $data, 'msg' => $msg];
}


/**
 * 根据ip定位
 * @param $ip
 * @return string
 * @throws Exception
 */
function getLocationByIp($ip)
{
    $ip2region = new \Ip2Region();
    $info = $ip2region->btreeSearch($ip);

    $info = explode('|', $info['region']);

    $address = '';
    foreach($info as $vo) {
        if('0' !== $vo) {
            $address .= $vo . '-';
        }
    }

    return rtrim($address, '-');
}

/**
 * 按钮检测
 * @param $input
 * @return bool
 */
function buttonAuth($input)
{
    $authModel = Auth::instance();
    return  $authModel->authCheck($input, session('admin_role_id'));
}

if (!function_exists('formatDate')) {
    /**
     * 格式化时间戳通用
     * @Author binx
     * @Date   2021-12-20
     * @param  integer    $timestamp [description]
     * @param  string     $format    [description]
     * @return [type]                [description]
     */
    function formatDate($timestamp=0, $format='Y-m-d H:i:s')
    {
        if (empty($timestamp)) {
            return '';
        }

        return date($format, $timestamp);
    }
}

if (!function_exists('uuid')) {
    /**
     * uuid方法
     * @Author zhibin
     * @Date   2019-11-18
     * @return [type]     [description]
     */
    function uuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid  = substr($chars,0,8) . '-';
        $uuid .= substr($chars,8,4) . '-';
        $uuid .= substr($chars,12,4) . '-';
        $uuid .= substr($chars,16,4) . '-';
        $uuid .= substr($chars,20,12);

        return $uuid;
    }
}

/**
 * 设置访问密码
 * 
 * @param $password  访问密码
 * @param $pageid    页面唯一 ID 值，用于区分同一网站的不同加密页面
 */
function MkEncrypt($password, $pageid='default') {
    $MK_ENCRYPT_SALT = 'Kgs$JC!V';
    $pageid     = md5($pageid);
    $md5pw      = md5(md5($password).$MK_ENCRYPT_SALT);
    $postpwd    = isset($_POST['pagepwd']) ? addslashes(trim($_POST['pagepwd'])) : '';
    $cookiepwd  = isset($_COOKIE['mk_encrypt_'.$pageid]) ? addslashes(trim($_COOKIE['mk_encrypt_'.$pageid])) : '';
    
    // setcookie('mk_encrypt_' . $pageid, NULL, -1, '/'); //设置过期s

    if($cookiepwd == $md5pw) return ;    // Cookie密码验证正确
    if($postpwd === $password) {// 提交的密码正确
        setcookie('mk_encrypt_' . $pageid, $md5pw, time() + 3600000, '/');
        return ;
    }

    if ($postpwd) $is_error = 1;
    else $is_error = 0;

    $Object = \think\Response::create('common/default', 'view')->assign([
        'is_error' => $is_error,
    ])->send();
}

if (!function_exists('pre')) {
    /**
     * 调试方法
     * @Author zhibin
     * @Date   2019-11-18
     * @param  string     $data [description]
     * @return [type]           [description]
     */
    function pre($data='')
    {
        $args = func_get_args();
        $num =  func_num_args();
        $is_cli = preg_match("/cli/i", php_sapi_name());
        $br =  $is_cli? PHP_EOL : '<br/>';

        echo $is_cli ? '' : '<pre style="white-space:pre-wrap;word-wrap:break-word;">';
        for ($i=0; $i < $num; $i++) { 
            print_r($args[$i]);
            echo $br;
        }
        echo $is_cli ? '' : '</pre>';
    }
}

if (!function_exists('my_sort')) {
    /**
     * 二维数组排序
     * @Author zhibin
     * @Date   2018-07-31
     * @param  [type]     $arrays     [description]
     * @param  [type]     $sort_key   [description]
     * @param  [type]     $sort_order [description]
     * @param  [type]     $sort_type  [description]
     * @return [type]                 [description]
     */
    function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){  
        if(is_array($arrays)){  
            foreach ($arrays as $array){  
                if(is_array($array)){  
                    $key_arrays[] = $array[$sort_key];  
                }else{  
                    return false;  
                }  
            }  
        }else{  
            return false;  
        } 
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);  
        return $arrays;  
    }
}

if (!function_exists('keeplog')) {
    /**
     * 记录日志
     * \think\Config::set('log.type', 'test'); //关闭controller=>function页面访问日志
     * @Author   zhibin
     * @DateTime 2018-07-04
     */
    function keeplog($data=null, $file_name='alarm', $request=null, $suffix='log', $filename_ext='')
    {
        if (is_array($data)) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        }

        if (is_array($request)) {
            $request = json_encode($request, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
        }

        $datetime = date('Y-m-d H:i:s');
        $dir = RUNTIME_PATH.'log';
        if (is_dir($dir) && !is_writable($dir)) {
            return ['code'=>500, 'msg'=>"[{$dir}]Permission denied"];
        }

        $log_dir = $dir.'/'.date('Ym');
        if (is_dir($log_dir) && !is_writable($log_dir)) {
            return ['code'=>500, 'msg'=>"[{$log_dir}]Permission denied"];
        }

        //防止写日志错误导致业务程序受影响
        try {
            if (!is_dir($log_dir)) {
               mkdir($log_dir, 0777) && chmod($log_dir, 0777);
            }
            
            empty($filename_ext) && $filename_ext = date('Ymd');
            empty($file_name) && $file_name = md5(microtime());
            $dir_path = $log_dir.'/'.$file_name.'_'.$filename_ext.'.'.$suffix;
            file_put_contents($dir_path, 'date:'.$datetime."\ndata:".$data."\nrequest:".$request."\n\n", FILE_APPEND);
            chmod($dir_path, 0777);

            $code = 200;
            $msg = 'Success';
        } catch (\Exception $e) {
            $code = 500;
            $msg = $e->getMessage();
            // pre($code, $msg);
        }

        return ['code'=>$code, 'msg'=>$msg];
    }
}

if (!function_exists('pushtask')) {
    /**
     * 投递任务
     * @Author zhibin
     * @Date   2020-06-11
     * @param  [type]     $url  [description]
     * @param  array      $data [description]
     * @return [type]           [description]
     */
    function pushtask(array $data, $task_name='import_demo', $log_id=0, $port=9502)
    {
        if (!class_exists('swoole_client')) {
            return false;
        }

        try{
            $server_ip = '127.0.0.1';
            $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);
            $res = $client->connect($server_ip, $port);
            if(!empty($res)) {

                //data数据压缩方式 json|serialize
                $data_compress_method = 'json';
                if (isset($data['data_compress_method'])) {
                    $data_compress_method ='serialize';
                    unset($data['data_compress_method']);
                }

                $data_compress_method=='serialize' && $data = serialize($data); //解决传递对象问题
                $send_data = ['task_name'=>$task_name, 'data'=>$data, 'data_compress_method'=>$data_compress_method, 'log_id'=>$log_id];
                $client->send(json_encode($send_data));
                // $ret = $client->recv(); //从服务器接收数据
                $client->close();
                return true;
            }
        } catch (\Exception $e) {
            return false;
        }
    }
}